home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4893 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.8 KB  |  64 lines

  1. Path: columba.udac.uu.se!news
  2. From: Enrico Savazzi <enrico.savazzi@pal.uu.se>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Help! Allocating 3 dimensional or greater arrays in C++
  5. Date: Thu, 01 Feb 1996 15:53:43 +0100
  6. Organization: Uppsala University
  7. Message-ID: <3110D3F7.51B1@pal.uu.se>
  8. References: <310CD09F.1D71@ns.vvm.com>
  9. NNTP-Posting-Host: esavazzi.pal.uu.se
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b5 (WinNT; I)
  14.  
  15. Arun Nair wrote:
  16. > I have been trying to allocate a 3 dimensional array in C++.
  17. > void main()
  18. > {
  19. >         int *matrix;
  20. >         int **pmatrix = &matrix;
  21. >         int ***ppmatrix = &pmatrix;
  22. >         int size;
  23. >         matrix = new int[10];
  24. >         pmatrix = new matrix[10];
  25. >         ppmatrix = new pmatrix[10];
  26. >         .
  27. >         .
  28. >         .
  29. >         .
  30. >         What is wrong with the above code?  I have searched the
  31. > C++ faqs and a couple of other books for this answer but so far
  32. > I have not been able to get an answer.  If any of you can help me
  33. > in this regard I would be grateful.
  34. > Thanks in advance,
  35. > with best regards,
  36. > Arun
  37. > (arun@ns.vvm.com)
  38.  
  39. Let's say you want a three-dimensional array, 10 by 10 by 10 elements:
  40.  
  41. int*** a;
  42. a = new int** [10];
  43. for (int i = 0; 1 < 10; i++)
  44. {
  45.     a[i] = new int* [10];
  46.     for (int j = 0; j < 10; j++)
  47.         a[i][j] = new int [10];
  48. }
  49.  
  50. You have first to create an array of pointers to pointers to integer arrays, then 
  51. create arrays of pointers to integers, then allocate integer elements to each of these 
  52. arrays. For higher dimensions, add more allocation loops. Access the array elements in 
  53. the usual way (a[i][j][k]). Delete the array in reverse order. If you want to cut on 
  54. execution time, use a one-dimensional array and do the pointer arithmetics explicitly 
  55. - I usually do.
  56.  
  57. Enrico Savazzi
  58.